#!/bin/sh

echo "git_clone_and_fetch: $GIT_REPO_URL branch: $GIT_REPO_BRANCH"

remove_lock_files () {
  echo "It's a git repo"
  if [ -f "$LOCAL_REPO_PATH/.git/shallow.lock" ]; then
    echo "shallow.lock found. delete it."
    rm -f "$LOCAL_REPO_PATH/.git/shallow.lock"
  else
    echo "no shallow.lock"
  fi

  if [ -f "$LOCAL_REPO_PATH/.git/index.lock" ]; then
    echo "index.lock found. delete it."
    rm -f "$LOCAL_REPO_PATH/.git/index.lock"
  else
    echo "no index.lock"
  fi

}

clone_main_repo() {
  git config --global --add safe.directory "$LOCAL_REPO_PATH"
  if [ -d "$LOCAL_REPO_PATH/.git" ]; then
    echo "It's a git repo. Only fetch."
  else
    git clone $GIT_REPO_URL "$LOCAL_REPO_PATH"
  fi
  cd "${LOCAL_REPO_PATH}"
  echo "start git fetch new files"
  
  git fetch origin $GIT_REPO_BRANCH && git reset --hard "origin/$GIT_REPO_BRANCH"

  if [ -n "$REPO_COMMIT_ID" ]; then
    git checkout $REPO_COMMIT_ID
  fi
}

remove_lock_files
clone_main_repo

exit_code=$?
if [ $exit_code -eq 128 ]; then
  echo "git clone error code: "$exit_code
  if [ -d "$LOCAL_REPO_PATH/.git" ]; then
    echo "It's a git repo"
    remove_lock_files
  else
    echo "no .git dir"
    git init
  fi

  git remote -v
  git remote remove origin
  echo "change git remote url"
  git remote add origin $GIT_REPO_URL
  git remote -v
  clone_main_repo
fi